package com.starsea.book.ui.newpage.normalview

import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import com.starsea.book.ui.newpage.normalview.delegate.RadiusTextViewDelegate

/**
 * @author Lee
 * @createTime 2023-07-27 17 GMT+8
 * @desc :
 */
class RadiusTextView @JvmOverloads constructor(
  context: Context?,
  attrs: AttributeSet? = null,
  defStyleAttr: Int = 0,
) :
  AppCompatTextView(context!!, attrs, defStyleAttr) {
  private val delegate: RadiusTextViewDelegate?

  init {
    delegate = RadiusTextViewDelegate(this, context, attrs)
  }

  /**
   * 获取代理类用于代码控制shape属性
   *
   * @return
   */
  fun getDelegate(): RadiusTextViewDelegate? {
    return delegate
  }

  override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
    if (delegate != null && delegate.widthHeightEqualEnable && width > 0 && height > 0) {
      val max = Math.max(width, height)
      val measureSpec = MeasureSpec.makeMeasureSpec(max, MeasureSpec.EXACTLY)
      super.onMeasure(measureSpec, measureSpec)
      return
    }
    super.onMeasure(widthMeasureSpec, heightMeasureSpec)
  }

  override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
    super.onLayout(changed, left, top, right, bottom)
    if (delegate != null) {
      if (delegate.radiusHalfHeightEnable) {
        delegate.setRadius(height / 2F)
      }
      delegate.init()
    }
  }

  override fun setSelected(selected: Boolean) {
    super.setSelected(selected)
    delegate?.setSelected(selected)
  }

  override fun setEnabled(enabled: Boolean) {
    super.setEnabled(enabled)
    delegate?.init()
  }
}
